/**
 * @param {string[]} words
 * @param {string} order
 * @return {boolean}
 */
export var isAlienSorted = function (words, order) {
  const orderDict = {}
  // 越小越前
  for (let i = 0; i < order.length; i++) {
    orderDict[order[i]] = i
  }
  for (let i = 0; i < words.length - 1; i++) {
    const [word1, word2] = [words[i], words[i + 1]]
    let allSame = true
    for (let j = 0; j < Math.min(word1.length, word2.length); j++) {
      if (orderDict[word1[j]] > orderDict[word2[j]]) {
        return false
      } else if (orderDict[word1[j]] < orderDict[word2[j]]) {
        allSame = false
        break
      }
    }
    if (allSame && word1.length > word2.length) {
      return false
    }
  }
  return true
}

/**
 * 这方法比上边方法快
 * @param {string[]} words
 * @param {string} order
 * @return {boolean}
 */
export var isAlienSorted2 = function (words, order) {
  let map = new Map()
  // 注：这样映射, 对应的数字越小, 字典序越大
  for (let i = 0; i < order.length; i++) map.set(order[i], i)
  // JS 中字符串取超出长度时为 undefined, 设置为最大字典序
  map.set(undefined, -1)
  // 单词之间两两比较
  for (let i = 0; i < words.length - 1; i++) {
    for (let j = 0; j < Math.max(words[i].length, words[i + 1].length); j++) {
      // 相同字母, 跳到下轮比较
      if (words[i][j] == words[i + 1][j]) continue
      // 前面的字母字典序中比较小(数字大), 则返回 false
      else if (map.get(words[i][j]) > map.get(words[i + 1][j])) return false
      // 前面的字母字典序比较大, 进入 下两个单词的比较
      else break
    }
  }
  return true
}
